package net.mujiwulian.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import net.mujiwulian.entity.Video;
import net.mujiwulian.service.VideoService;
import net.mujiwulian.vo.PageQuery;
import net.mujiwulian.vo.Result;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * @Author: silence
 * @Description:
 * @Date:Create：in 2019/12/30 12:44
 */
@Slf4j
@RestController
@RequestMapping("/video")
public class VideoController {

    @Value("${file-path}")
    private String filePath;

    private final VideoService videoService;

    public VideoController(VideoService videoService) {
        this.videoService = videoService;
    }

    @PostMapping("/select")
    public Result<IPage<Video>> select(@RequestBody PageQuery<Video> pageQuery) {
        LambdaQueryWrapper<Video> lq = Wrappers.lambdaQuery();
        lq.and(StringUtils.isNotEmpty(pageQuery.getKeywords()), i -> i.like(Video::getAuthor, pageQuery.getKeywords()).or().like(Video::getTitle, pageQuery.getKeywords()));
        lq.orderByDesc(Video::getCreateTime);
        return new Result<>(Result.CodeStatus.OK, "获取视频信息", videoService.page(pageQuery.getPageCondition(), lq));
    }

    @PostMapping("/delete")
    public Result<Void> delete(@RequestBody List<Integer> ids) {
        List<Video> list = videoService.list(new QueryWrapper<Video>().in("id", ids).select("cover_url"));
        list.forEach(document -> log.warn("删除文件:" + document.getCoverUrl() + "-----" + new File(this.filePath + document.getCoverUrl()).delete()));
        return new Result<>("删除视频", videoService.removeByIds(ids));
    }

    @PostMapping("/insertOrUpdate")
    public Result<Void> insertOrUpdate(Video video) {
        Video vo = null;
        if (video.getId() != null) {
            video.setCreateTime(null);
            vo = videoService.getById(video.getId());
        } else {
            if (!videoService.list(new QueryWrapper<Video>().eq("title", video.getTitle())).isEmpty()) {
                return new Result<>(Result.CodeStatus.FAIL, "标题已存在");
            }
            video.setCreateTime(LocalDateTime.now());
        }
        try {
            if (video.getCover() != null) {
                String path = "/files/video/" + UUID.randomUUID().toString() + video.getCover().getOriginalFilename();
                FileUtils.copyInputStreamToFile(video.getCover().getInputStream(), new File(this.filePath + path));
                video.setCoverUrl(path);
                if (vo != null) {
                    File deleteFile = new File(this.filePath + vo.getCoverUrl());
                    log.warn("删除文件:" + vo.getCoverUrl() + "-----" + deleteFile.delete());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new Result<>(Result.CodeStatus.FAIL, "网络异常");
        }
        return new Result<>("操作", videoService.saveOrUpdate(video));
    }


}
